<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Todo List</title>
		<link rel="stylesheet" href="css/base.css">
		<link rel="stylesheet" href="css/index.css">
		<link rel="stylesheet" href="css/nprogress.css">
	</head>
	<body>
		<section class="todoapp">
			<header class="header">
				<h1>todos</h1>
				<input class="new-todo" placeholder="What needs to be done?" autofocus id="task">
			</header>
			<!-- This section should be hidden by default and shown when there are todos -->
			<section class="main">
				<input class="toggle-all" type="checkbox">
				<label for="toggle-all">Mark all as complete</label>
				<ul class="todo-list" id="todo-list">
					<!-- These are here just to show the structure of the list items -->
					<!-- List items should get the class `editing` when editing and `completed` when marked as completed -->
				</ul>
			</section>
			<!-- This footer should hidden by default and shown when there are todos -->
			<footer class="footer">
				<!-- This should be `0 items left` by default -->
				<span class="todo-count"><strong id="count">0</strong> item left</span>
				<!-- Remove this if you don't implement routing -->
				<ul class="filters">
					<li>
						<a class="selected" href="#/">All</a>
					</li>
					<li>
						<a href="#/active">Active</a>
					</li>
					<li>
						<a href="#/completed">Completed</a>
					</li>
				</ul>
				<!-- Hidden if no completed items are left ↓ -->
				<button class="clear-completed">Clear completed</button>
			</footer>
		</section>
		<script src="js/jquery.min.js"></script>
		<script src="js/template-web.js"></script>
		<script src="js/nprogress.js"></script>
		<script id="taskTpl" type="text/html">
			{{each tasks}}
			<li class="{{$value.completed ? 'completed':''}}">
				<div class="view">
					<input class="toggle" type="checkbox" {{$value.completed?'checked':''}} >
					<label>{{$value.title}}</label>
					<button class="destroy" data-id="{{$value._id}}"></button>
				</div>
				<input class="edit" value="Create a TodoMVC template">
			</li>
			{{/each}}
		</script>
		<script type="text/javascript">
			//用于存放任务列表的数组
			var taskAry = [];
			//获取页面元素
			var taskBox = $('#todo-list');
			var taskInp =$('#task');
			var strong = $('#count');
			//绑定ajax全局事件
			$(document).on('ajaxStart',function () {
				NProgress.start();
			});
			$(document).on('ajaxComplete',function () {
				NProgress.done();
			});
			//获取当前数据库存在的任务，并展示在页面中
			$.ajax({
				url: 'todo/task',
				type: 'get',
				success: function (response) {
					console.log(response);
					taskAry = response;
					render();
					calCount();
				}
			});
			//添加任务，文本框输入回车键
			taskInp.on('keyup',function (e) {
				if(e.keyCode == 13){
					var taskName = $(this).val();
					if(taskName.trim().length == 0){
						alert('未输入任务')
						return;
					}else {
						$.ajax({
							url: '/todo/addTask',
							type: 'post',
							data: JSON.stringify({title: taskName}),
							contentType: 'application/json',
							success: function (response) {
								taskAry.push(response);
								render();
								calCount();
								taskInp.val('');
							}
						})
					}
				}

			});
			//删除任务，用事件委托
			taskBox.on('click','.destroy',function () {
				//获取按钮上绑定的id属性
				var id = $(this).attr('data-id');
				//向服务器发送删除任务请求
				$.ajax({
					type: 'get',
					url: 'todo/deleteTask',
					data: {
						_id: id
					},
					success: function (response) {
						//从任务数组中找到删除的任务索引
						var index = taskAry.findIndex(item => item._id == id);
						//根据索引号删除该项
						taskAry.splice(index,1);
						//重新渲染任务列表
						render();
						calCount();
					}
				})
			})
			//更改任务状态,勾选任务名称前面的复选框触发
			taskBox.on('change','.toggle',function () {
				const status = $(this).is(':checked');
				const id = $(this).siblings('button').attr('data-id');
				$.ajax({
					url:'todo/modifyTask',
					type: 'post',
					data: JSON.stringify({_id: id,	completed: status}),
					contentType: 'application/json',
					success: function (response) {
						//将返回的数据同步到任务列表的数组中
						var task = taskAry.find(item => item._id == id);
						task.completed = response.completed;
						render();
						calCount();
					}
				})
			});
			//双击任务名称可以标记事件，同时给外层的li添加editing类名
			taskBox.on('dblclick','label',function () {
				//让任务处于编辑状态
				$(this).parent().parent().addClass('editing');
				//让任务名称显示在文本框内
				$(this).parent().siblings('input').val($(this).text());
				//让文本框获取焦点
				$(this).parent().siblings('input').focus();
			});
			//文本框失去焦点时，让当前任务名称改变
			taskBox.on('blur','.edit',function () {
				var newTaskName = $(this).val();
				var id = $(this).siblings().find('button').attr('data-id');
				$.ajax({
					url: 'todo/modifyTask',
					type:'post',
					data: JSON.stringify({_id:id,title: newTaskName}),
					contentType: 'application/json',
					success: function (response) {
						var task = taskAry.find(item => item._id == id);
						task.title = response.title;
						render();
						calCount();
					}
				})
			});

			//渲染页面
			function render(){
				var html = template('taskTpl',{
					tasks: taskAry
				});
				taskBox.html(html);
			}
			//计算未完成任务的数量
			function calCount() {
				var count = 0;
				//将未完成的任务放在新数组中
				var newAry = taskAry.filter(item => item.completed ==false);
				count = newAry.length;
				strong.text(count);
			}
		</script>
	</body>
</html>
